import os

import requests
from flask import Blueprint, jsonify,request
from server.resource.util.ApiResponse import ApiResponse
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS


bp = Blueprint("MetaData", __name__, url_prefix="/MetaData")

@bp.route('/getGPS',methods=['POST'])
def getGPS():
    data = request.get_json()
    file_url = data[('file_url')]
    # getImage(file_url)
    path = 'server/static/image.jpg'
    try:
        image = Image.open(path)
        exif_dict = {}
        exifdata = image.getexif()
        print(len(exifdata))
        for tag, value in exifdata.items():
            if tag in TAGS:
                exif_dict[TAGS[tag]] = value
        if 'GPSInfo' in exif_dict:
            print("yes")
            # 解析 GPSInfo 标签中的子标签
            gps_data = {}
            for gps_tag in exif_dict['GPSInfo'].keys():
                print(1)
                tag_name = GPSTAGS.get(gps_tag, gps_tag)
                gps_data[tag_name] = exif_dict['GPSInfo'][gps_tag]
            exif_dict['GPSInfo'] = gps_data
        return jsonify(ApiResponse.success(exif_dict))
    except Exception as e:
        return jsonify(ApiResponse.server_error(str(e)))

@bp.route('/getAll', methods=['POST'])
def getMetaData():
    data = request.get_json()
    file_url = data['file_url']
    # 替换这里的链接为正确的直接下载链接
    # file_url = "https://image.zzzsleep.icu/6609652f57c8d.jpg"
    print(file_url)
    getImage(file_url)
    path = 'server/static/image.jpg'
    try:
        image = Image.open(path)
        # 创建一个字典来存储 EXIF 数据
        exif_dict = {}
        exifdata = image.getexif()
        print(len(exifdata))
        for tag, value in exifdata.items():
            if tag in TAGS:
                tagname = TAGS[tag]
                exif_dict[tagname] = value
                print(f"{tagname:25}: {value}")
                exif_dict[f'{tagname}'] = f'{value}'
        return jsonify(ApiResponse.success(exif_dict))
    except Exception as e:
        return jsonify(ApiResponse.server_error(str(e)))

def getImage(image_url, save_path='server/static/image.jpg'):
    try:
        # 发送GET请求，使用环境变量或正确的证书路径来验证SSL
        response = requests.get(image_url, verify=True)  # 假设您有一个有效的证书路径
        if response.status_code == 200:
            # 检查目录是否存在，如果不存在则创建
            os.makedirs(os.path.dirname(save_path), exist_ok=True)
            # 图片请求成功，保存图片
            with open(save_path, 'wb') as file:
                file.write(response.content)
            print("图片下载成功，已保存为", save_path)
        else:
            # 请求失败，输出错误信息
            print(f"图片下载失败，状态码：{response.status_code}")
    except requests.exceptions.RequestException as e:
        # 请求异常处理
        print(f"请求图片时发生错误：{e}")
    except IOError as e:
        # 文件写入异常处理
        print(f"保存图片时发生错误：{e}")